import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { Notification } from 'element-ui'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  accountId: '',
  mobilePhone: '',
  roleType: '',
  roleName: '',
  organization: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ACCOUNT_ID: (state, accountId) => {
    state.accountId = accountId
  },
  SET_MOBILEPHONE: (state, mobilePhone) => {
    state.mobilePhone = mobilePhone
  },
  SET_ROLENAME: (state, roleName) => {
    state.roleName = roleName
  },
  SET_ORGANIZATION: (state, organization) => {
    state.organization = organization
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    // 获取账号 密码
    const { username, password, roleType } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, roleType: roleType }).then(response => {
        console.log('login', response)
        if (response.code === 200) {
          Notification.success({
            title: '成功',
            message: '登录成功'
          })
          const { data } = response
          commit('SET_TOKEN', data)
          setToken(data)
          resolve(response)
        } else {
          Notification.error({
            title: '失败',
            message: '登录失败，请重试'
          })
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        console.log('userInfo', response.data)
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const role = []
        role.push(data.roleType)
        data.roles = role
        data.name = data.username
        data.introduction = data.description

        const { roles, name, avatar, introduction, accountId, mobilePhone, roleName, organization } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        // 如果头像为空
        if (avatar === '' || avatar === null) {
          avatar = `https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif`
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_ACCOUNT_ID', accountId)
        commit('SET_MOBILEPHONE', mobilePhone)
        commit('SET_ROLENAME', roleName)
        commit('SET_ORGANIZATION', organization)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then((res) => {
        if (res.code === 200) {
          Notification.success({
            title: '成功',
            message: '退出登录成功'
          })
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resetRouter()
        } else {
          Notification.error({
            title: '失败',
            message: '退出登录失败'
          })
        }

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
